package com.wzdigit.wms.wms.service.mid;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wzdigit.mes.basic.api.BasicDataItemDetailApi;
import com.wzdigit.mes.basic.api.BasicGetCustomerApi;
import com.wzdigit.mes.basic.api.BasicSimpleCodeRuleApi;
import com.wzdigit.mes.basic.dto.DataItemDetailDTO;
import com.wzdigit.wms.basic.domain.asn.AsnDtl;
import com.wzdigit.wms.basic.domain.asn.AsnHeader;
import com.wzdigit.wms.basic.domain.basic.Sku;
import com.wzdigit.wms.basic.domain.basic.Warehouse;
import com.wzdigit.wms.basic.domain.inventory.Lotno;
import com.wzdigit.wms.basic.domain.mapping.CodeMapping;
import com.wzdigit.wms.basic.domain.mid.IfRepackdeliveryDtl;
import com.wzdigit.wms.basic.domain.mid.IfRepackdeliveryHeader;
import com.wzdigit.wms.basic.domain.mid.JobSyncErrorData;
import com.wzdigit.wms.basic.domain.mid.dtos.IfRepackdeliveryHeaderDto;
import com.wzdigit.wms.basic.domain.transfer.GdnDtl;
import com.wzdigit.wms.basic.domain.transfer.GdnHeader;
import com.wzdigit.wms.basic.enums.*;
import com.wzdigit.wms.basic.mapper.core.basic.SkuMapper;
import com.wzdigit.wms.basic.mapper.core.basic.WarehouseMapper;
import com.wzdigit.wms.basic.mapper.core.mid.IfRepackdeliveryDtlMapper;
import com.wzdigit.wms.basic.mapper.core.mid.IfRepackdeliveryHeaderMapper;
import com.wzdigit.wms.basic.mapper.core.mid.JobSyncErrorDataMapper;
import com.wzdigit.wms.basic.mapper.core.order.AsnDtlMapper;
import com.wzdigit.wms.basic.mapper.core.order.AsnHeaderMapper;
import com.wzdigit.wms.basic.mapper.core.transfer.GdnDtlMapper;
import com.wzdigit.wms.basic.mapper.core.transfer.GdnHeaderMapper;
import com.wzdigit.wms.wms.constant.SyncTypeConstant;
import com.wzdigit.wms.wms.exception.SyncException;
import com.wzdigit.wms.basic.service.code.LotnoService;
import com.wzdigit.wms.wms.service.mapping.CodeMappingNewService;
import net.dreamlu.mica.core.utils.BeanUtil;
import net.dreamlu.mica.core.utils.CollectionUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.jfree.util.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 接口中间表-返包出库单表头 服务类
 * </p>
 *
 * @author
 * @since 2021-03-16
 */
@Service
public class IfRepackdeliveryHeaderService {

    @Autowired
    private IfRepackdeliveryHeaderMapper ifRepackdeliveryHeaderMapper;

    @Autowired
    private IfRepackdeliveryDtlMapper ifRepackdeliveryDtlMapper;

    @Autowired
    private GdnHeaderMapper gdnHeaderMapper;

    @Autowired
    private GdnDtlMapper gdnDtlMapper;

    @Autowired
    private AsnHeaderMapper asnHeaderMapper;

    @Autowired
    private AsnDtlMapper asnDtlMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private LotnoService lotnoService;

    @Autowired
    private SyncErrorDataService syncErrorDataService;

    @Autowired
    private JobSyncErrorDataMapper jobSyncErrorDataMapper;

    @Autowired
    private WarehouseMapper warehouseMapper;

    @Reference(version = "${dubbo.providers.basic.customer.api.version:1.0.0}", check = false, timeout = 300000)
    private BasicGetCustomerApi basicGetCustomerApi;

    @Reference(version = "${dubbo.consumers.basic.data.item.detail.api:1.0.0}", check = false, timeout = 300000)
    private BasicDataItemDetailApi dataItemDetailApi;

    @Reference(version = "${dubbo.consumers.basic.simple.code.rule.api:1.0.0}", check = false)
    BasicSimpleCodeRuleApi basicSimpleCodeRuleApi;

    @Value(value = "${default_owner.code}")
    private String DEFAULT_OWNER;

    @Value(value = "${default_owner.name}")
    private String DEFAULT_OWNER_NAME;



    @Autowired
    private CodeMappingNewService codeMappingNewService;

    //    @Value("${order_code.gdn.code}")
    private String gdnNoRule = "GDN_D03";

    private final String syncType = SyncTypeConstant.IF_REPACKDELIVERY_TO_GDN;

    public List<IfRepackdeliveryHeaderDto> selectSyncData() {
        ArrayList<IfRepackdeliveryHeaderDto> ifRepackdeliveryHeaderDtos = new ArrayList<>();
        QueryWrapper<IfRepackdeliveryHeader> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("Attribute10","1").or().isNull("Attribute10");
        //queryWrapper.eq("BILL_NO","L21110900001");
        List<IfRepackdeliveryHeader> selectSyncData = ifRepackdeliveryHeaderMapper.selectList(queryWrapper);
        if (!CollectionUtil.isEmpty(selectSyncData)) {
            for (IfRepackdeliveryHeader ifRepackdeliveryHeader : selectSyncData) {
                IfRepackdeliveryHeaderDto ifRepackdeliveryHeaderDto = new IfRepackdeliveryHeaderDto();
                BeanUtil.copyNonNull(ifRepackdeliveryHeader, ifRepackdeliveryHeaderDto);
                List<IfRepackdeliveryDtl> ifRepackdeliveryDtlList = ifRepackdeliveryDtlMapper.selectList(new QueryWrapper<>(new IfRepackdeliveryDtl().setIfRepackdeliveryHeaderId(ifRepackdeliveryHeader.getIfRepackdeliveryHeaderId())));
                ifRepackdeliveryHeaderDto.setIfRepackdeliveryDtlList(ifRepackdeliveryDtlList);
                ifRepackdeliveryHeaderDtos.add(ifRepackdeliveryHeaderDto);
            }
        }
        return ifRepackdeliveryHeaderDtos;
    }

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public void syncData(IfRepackdeliveryHeaderDto data, boolean isSyncError) throws Exception {
        if("0".equals(data.getAttribute2())){//
            toWmsGdn(data);
        }else if("1".equals(data.getAttribute2())){//原材料

            if("1".equals(data.getAttribute3())){ //出库
                toRawGdn(data);
            }else if("2".equals(data.getAttribute3())){//入库
                toRawAsn(data);
            }else if("3-1".equals(data.getAttribute3())||"3-2".equals(data.getAttribute3())||"3-3".equals(data.getAttribute3())){
                toRawTransfer(data);
            }
        }

    }

    private void toRawTransfer(IfRepackdeliveryHeaderDto data) {
        //暂时没有这个业务，后面补充




    }


    private void toRawAsn(IfRepackdeliveryHeaderDto data) throws SyncException {
        String billNo = data.getBillNo(); //返包出库单号
        List<IfRepackdeliveryDtl> ifRepackdeliveryDtlList = data.getIfRepackdeliveryDtlList();
        if (CollectionUtil.isEmpty(ifRepackdeliveryDtlList)) {
            throw new SyncException(syncType, billNo, "该返包出库单下没有明细行");
        }
        

        Boolean isUpdate = true;

        AsnHeader asnHeader = asnHeaderMapper.selectOne(new QueryWrapper<>(new AsnHeader().setAsnNo(billNo)));
        if (asnHeader == null) {
            isUpdate = false;
            asnHeader = new AsnHeader();
        }
        BeanUtil.copyNonNull(data, asnHeader);
        //asnHeader.setSourceNo(billNo);
        asnHeader.setAsnNo(billNo);
        asnHeader.setFactory(data.getOrgCode());

        asnHeader.setAsnType(AsnTypeEnum.R11.code);
        asnHeader.setStatus(AsnHeaderStatusEnum.CREATE.code);
        asnHeader.setAsnCreateTime(data.getCreateTime());
        asnHeader.setAsnCreateUser(data.getCreateUser());
        asnHeader.setComments(data.getRemarks());
        DataItemDetailDTO dataItem = dataItemDetailApi.getDefaultDataItemDetailByCode(DEFAULT_OWNER);
        asnHeader.setOwner(dataItem == null || dataItem.getItemValue() == null ? 0 : Integer.parseInt(dataItem.getItemValue()));
        asnHeader.setPriority(0);
        asnHeader.setReleaseStatus(0);
        asnHeader.setSourceType(data.getBillType());
        asnHeader.setAsnRef1(data.getAttribute1());//同步字段 合格标识
        asnHeader.setAsnRef2(data.getAttribute2());//物料属性

        if (isUpdate) {
            asnHeader.setModifyTime(new Date());
            asnHeader.setModifyUser("system");
            asnHeaderMapper.updateById(asnHeader);
        } else {

            asnHeader.setQcStatus(QcStatusEnum.未创建质检单.getCode());
            asnHeader.setCreateTime(new Date());
            asnHeader.setCreateUser("system");
            asnHeaderMapper.insert(asnHeader);
        }
        for (IfRepackdeliveryDtl ifRepackdeliveryDtl : ifRepackdeliveryDtlList) {
            Boolean isUpdateDtl = true;
            AsnDtl asnDtl = asnDtlMapper.selectOne(new QueryWrapper<>(new AsnDtl().setAsnHeaderId(asnHeader.getAsnHeaderId()).setAsnLineNo(ifRepackdeliveryDtl.getBillLineNo())));
            if (asnDtl == null) {
                isUpdateDtl = false;
                asnDtl = new AsnDtl();
            }
            asnDtl.setAsnHeaderId(asnHeader.getAsnHeaderId());
            asnDtl.setSourceLineNo(ifRepackdeliveryDtl.getBillLineNo());
            asnDtl.setAsnLineNo(ifRepackdeliveryDtl.getBillLineNo());
            Sku sku = skuMapper.selectOne(new QueryWrapper<>(new Sku().setSkuCode(ifRepackdeliveryDtl.getMaterialCode())));
            if (sku == null) {
                throw new SyncException(syncType, billNo, "物料" + ifRepackdeliveryDtl.getMaterialCode() + "不存在");
            }
            asnDtl.setSkuId(sku.getSkuId());
            asnDtl.setSkuDesc(sku.getDescCn());
            asnDtl.setUnit(sku.getBaseUnit());
            asnDtl.setQcStatus(QcStatusEnum.未创建质检单.getCode());
            asnDtl.setOrderQty(ifRepackdeliveryDtl.getQty());
            asnDtl.setOrderQtyEa(ifRepackdeliveryDtl.getQty());
            CodeMapping codeMapping = new CodeMapping();
            if (ifRepackdeliveryDtl.getToWhs() != null && data.getOrgCode() != null) {
                codeMapping = codeMappingNewService.selectByMappingCodeAndFacCodeAnyOne(ifRepackdeliveryDtl.getToWhs(), data.getOrgCode());
                if (codeMapping!=null) {
                    Warehouse warehouse = warehouseMapper.selectOneByWhsCode(codeMapping.getWmsCode());

                    if (warehouse != null) {
                        asnDtl.setWhsId(warehouse.getWhsId());
                    }else{
                        asnDtl.setWhsId(0);
                    }
                }else{
                    throw new SyncException(syncType, billNo,  "根据仓库:" + ifRepackdeliveryDtl.getToWhs()+ "和工厂"+data.getOrgCode()+"没有找到映射仓库");
                }
            }else {
                throw new SyncException(syncType, billNo,  "仓库编码或者组织代码为空");
            }
            asnDtl.setAsnRef1(ifRepackdeliveryDtl.getToWhs()); //接收仓库
            asnDtl.setAsnRef2(ifRepackdeliveryDtl.getMfgPlant()); //分厂（制造工厂）
            asnDtl.setAsnRef3(ifRepackdeliveryDtl.getSourceId());  //来源单据号ID
            asnDtl.setAsnRef4(ifRepackdeliveryDtl.getSourceNo()); //来源单号
            asnDtl.setAsnRef5(ifRepackdeliveryDtl.getAttribute5()); //来源单据行号
            asnDtl.setUdf5(ifRepackdeliveryDtl.getFmWhs());//存对方库位
            //asnDtl.setAsnRef7(ifRepackdeliveryDtl.getMrpUser());  //MRP控制者
            //asnDtl.setAsnRef8(ifRepackdeliveryDtl.getMrpUserDesc()); //
            //asnDtl.setAsnRef9(ifRepackdeliveryDtl.getInspNo()); //送检单号
            //asnDtl.setWorkOrder(ifRepackdeliveryDtl.getPrdWo());
            asnDtl.setPoNo(ifRepackdeliveryDtl.getDemandNo());

            /*
            try {

                qaStatus = data.getAttribute1() == null ?
                        QaStatusEnum.WAIT.code : Integer.parseInt(data.getAttribute1());
            } catch (NumberFormatException e) {
                qaStatus = QaStatusEnum.OK.code;
            }*/
            Integer qaStatus  = null;
            //仓库不包含B和E 为合格
            if(ifRepackdeliveryDtl.getToWhs().indexOf("B")==-1&&ifRepackdeliveryDtl.getToWhs().indexOf("E")==-1){
                qaStatus = QaStatusEnum.OK.code;
            }else{
                qaStatus = QaStatusEnum.NG.code;
            }
            asnDtl.setQaStatus(qaStatus);  //QA状态

            if(qaStatus == QaStatusEnum.OK.code){
                asnDtl.setSoNo(ifRepackdeliveryDtl.getOldSoNo());
                asnDtl.setSoLineNo(ifRepackdeliveryDtl.getOldSoLineNo());
            } else {
                asnDtl.setSoNo(ifRepackdeliveryDtl.getNewSoNo());
                asnDtl.setSoLineNo(ifRepackdeliveryDtl.getNewSoLineNo());
            }
            asnDtl.setComments(ifRepackdeliveryDtl.getRemarks());
            asnDtl.setStatus(AsnDtlStatusEnum.CREATE.getCode());
            asnDtl.setAsnNo(asnHeader.getAsnNo());
            //asnDtl.setWorkCenter(ifRepackdeliveryDtl.getWorkCenter());
           try {
               if (isUpdateDtl) {
                   asnDtl.setModifyUser("system");
                   asnDtl.setModifyTime(new Date());
                   asnDtlMapper.updateById(asnDtl);
               } else {
                   asnDtl.setCreateUser("system");
                   asnDtl.setCreateTime(new Date());
                   asnDtlMapper.insert(asnDtl);
               }
           }catch(Exception e) {
               Log.info(e.getMessage());
               throw new SyncException(syncType, billNo, "插入或者更新失败");

           }

           
        }
        //更新状态为已同步
        int row = ifRepackdeliveryHeaderMapper.updateFlagById(data.getIfRepackdeliveryHeaderId());
        //检查是否有同步失败的记录，有则更新为成功
        JobSyncErrorData jobSyncErrorData = jobSyncErrorDataMapper.getSyncErrorDataByTypeAndCode(syncType, billNo);
        if (jobSyncErrorData != null && 0 == jobSyncErrorData.getIsSuccess()) {
            syncErrorDataService.updateSuccessByCode(syncType, billNo);
        }
    }

    private void toRawGdn(IfRepackdeliveryHeaderDto data) throws SyncException {
        String billNo = data.getBillNo(); //单号
        List<IfRepackdeliveryDtl> ifRepackdeliveryDtlList = data.getIfRepackdeliveryDtlList();
        if (CollectionUtil.isEmpty(ifRepackdeliveryDtlList)) {
            throw new SyncException(syncType, billNo, "该生产领料单下没有明细行");
        }
        Boolean isUpdate = true;
        GdnHeader gdnHeader = gdnHeaderMapper.selectOne(new QueryWrapper<>(new GdnHeader().setGdnNo(billNo)));
        if (gdnHeader == null) {
            isUpdate = false;
            gdnHeader = new GdnHeader();
        }
        BeanUtil.copyNonNull(data, gdnHeader);
        gdnHeader.setFactory(data.getOrgCode());
        gdnHeader.setGdnNo(data.getBillNo());
        if("D".equals(data.getBillType())||"Z".equals(data.getBillType())){
            gdnHeader.setGdnType(GdnTypeEnum.D02.code);//多次过帐
        }else{
            gdnHeader.setGdnType(GdnTypeEnum.D28.code);//一次过帐
        }

        gdnHeader.setStatus(GdnHeaderStatusEnum.CREATE.code);
        gdnHeader.setGdnCreateTime(data.getCreateTime());
        gdnHeader.setGdnCreateUser(data.getCreateUser());
        gdnHeader.setComments(data.getRemarks());
        DataItemDetailDTO dataItem = dataItemDetailApi.getDefaultDataItemDetailByCode(DEFAULT_OWNER);
        gdnHeader.setOwner(dataItem == null || dataItem.getItemValue() == null ? 0 : Integer.parseInt(dataItem.getItemValue()));
        gdnHeader.setPriority(0);
        gdnHeader.setGdnRef1(data.getAttribute1());//同步字段 合格标识
        gdnHeader.setGdnRef2(data.getAttribute2());//物料属性
        gdnHeader.setSourceType(data.getBillType());//单据类型
       // gdnHeader.setShipDate(data.getOnline)//
        if (isUpdate) {
            gdnHeader.setModifyTime(new Date());
            gdnHeader.setModifyUser("system");
            gdnHeaderMapper.updateById(gdnHeader);
        } else {
            gdnHeader.setCreateTime(new Date());
            gdnHeader.setCreateUser("system");
            gdnHeaderMapper.insert(gdnHeader);
        }
        Integer gdnLineNo = gdnDtlMapper.selectMaxLineId(gdnHeader.getGdnHeaderId());
        if(gdnLineNo == null){
            gdnLineNo =  0;
        }
        for (IfRepackdeliveryDtl ifRepackdeliveryDtl : ifRepackdeliveryDtlList) {
            Boolean isUpdateDtl = true;
            GdnDtl gdnDtl = gdnDtlMapper.selectOne(new QueryWrapper<>(new GdnDtl().setGdnHeaderId(gdnHeader.getGdnHeaderId()).setGdnRef5(ifRepackdeliveryDtl.getAttribute5())));
            if (gdnDtl == null) {
                isUpdateDtl = false;
                gdnDtl = new GdnDtl();
                gdnDtl.setGdnLineNo(++gdnLineNo);//加个GDN_LINE_NO
            }
            gdnDtl.setGdnHeaderId(gdnHeader.getGdnHeaderId());
            gdnDtl.setSourceShipNoticeItem(ifRepackdeliveryDtl.getBillLineNo());
            Sku sku = skuMapper.selectOne(new QueryWrapper<>(new Sku().setSkuCode(ifRepackdeliveryDtl.getMaterialCode())));
            if (sku == null) {
                throw new SyncException(syncType, billNo, "物料" + ifRepackdeliveryDtl.getMaterialCode() + "不存在");
            }
            gdnDtl.setSkuId(sku.getSkuId());
            gdnDtl.setUnit(sku.getBaseUnit());
            gdnDtl.setOrderQty(ifRepackdeliveryDtl.getQty());
            CodeMapping codeMapping = null;
            if (ifRepackdeliveryDtl.getFmWhs() != null && data.getOrgCode() != null) {
                codeMapping = codeMappingNewService.selectByMappingCodeAndFacCodeAnyOne(ifRepackdeliveryDtl.getFmWhs(), data.getOrgCode());
                if (codeMapping!=null) {
                    Warehouse warehouse = warehouseMapper.selectOneByWhsCode(codeMapping.getWmsCode());
                    if (warehouse != null) {
                        gdnDtl.setWhsId(warehouse.getWhsId());
                    }
                }else{
                    throw new SyncException(syncType, billNo,  "根据仓库:" + ifRepackdeliveryDtl.getToWhs()+ "和工厂"+data.getOrgCode()+"没有找到映射仓库");
                }
            }
            gdnDtl.setGdnRef1(ifRepackdeliveryDtl.getToWhs()); //接收仓库
            gdnDtl.setGdnRef2(ifRepackdeliveryDtl.getMfgPlant()); //分厂（制造工厂）
            gdnDtl.setGdnRef3(ifRepackdeliveryDtl.getSourceId());  //来源单据号ID
            gdnDtl.setGdnRef4(ifRepackdeliveryDtl.getSourceNo()); //来源单号
            gdnDtl.setGdnRef5(ifRepackdeliveryDtl.getAttribute5()); //来源单据行号
            gdnDtl.setGdnRef7(ifRepackdeliveryDtl.getMrpUser());  //MRP控制者
            gdnDtl.setGdnRef8(ifRepackdeliveryDtl.getMrpUserDesc()); //
            gdnDtl.setGdnRef9(ifRepackdeliveryDtl.getInspNo()); //送检单号
            gdnDtl.setWorkOrder(ifRepackdeliveryDtl.getPrdWo());
            gdnDtl.setPoNo(ifRepackdeliveryDtl.getDemandNo());
            Integer qaStatus = codeMapping.getQaStatus();
         /*   try {
                qaStatus = data.getAttribute1() == null ?
                        QaStatusEnum.WAIT.code : Integer.parseInt(data.getAttribute1());
            } catch (NumberFormatException e) {
                qaStatus = QaStatusEnum.OK.code;
            }*/
            gdnDtl.setQaStatus(qaStatus);  //QA状态

            if(qaStatus == QaStatusEnum.OK.code){
                gdnDtl.setSoNo(ifRepackdeliveryDtl.getOldSoNo());
                gdnDtl.setSoLineNo(ifRepackdeliveryDtl.getOldSoLineNo());
            } else {
                gdnDtl.setSoNo(ifRepackdeliveryDtl.getNewSoNo());
                gdnDtl.setSoLineNo(ifRepackdeliveryDtl.getNewSoLineNo());
            }
            gdnDtl.setComments(ifRepackdeliveryDtl.getRemarks());
            gdnDtl.setStatus(GdnDtlStatusEnum.CREATE.getCode());
            gdnDtl.setWorkCenter(ifRepackdeliveryDtl.getWorkCenter());

            if (isUpdateDtl) {
                gdnDtl.setModifyUser("system");
                gdnDtl.setModifyTime(new Date());
                gdnDtlMapper.updateById(gdnDtl);
            } else {
                gdnDtl.setCreateUser("system");
                gdnDtl.setCreateTime(new Date());
                gdnDtlMapper.insert(gdnDtl);
            }

        }
        //更新状态为已同步
        int row = ifRepackdeliveryHeaderMapper.updateFlagById(data.getIfRepackdeliveryHeaderId());
        //检查是否有同步失败的记录，有则更新为成功
        JobSyncErrorData jobSyncErrorData = jobSyncErrorDataMapper.getSyncErrorDataByTypeAndCode(syncType, billNo);
        if (jobSyncErrorData != null && 0 == jobSyncErrorData.getIsSuccess()) {
            syncErrorDataService.updateSuccessByCode(syncType, billNo);
        }
    }



    private void toWmsGdn(IfRepackdeliveryHeaderDto data) throws SyncException {
        String billNo = data.getBillNo(); //返包出库单号
        List<IfRepackdeliveryDtl> ifRepackdeliveryDtlList = data.getIfRepackdeliveryDtlList();
        if (CollectionUtil.isEmpty(ifRepackdeliveryDtlList)) {
            throw new SyncException(syncType, billNo, "该返包出库单下没有明细行");
        }


        Boolean isUpdate = true;

        GdnHeader gdnHeader = gdnHeaderMapper.selectOne(new QueryWrapper<>(new GdnHeader().setSourceShipNotice(billNo)));
        if (gdnHeader == null) {
            isUpdate = false;
            gdnHeader = new GdnHeader();
        }
        BeanUtil.copyNonNull(data, gdnHeader);
        gdnHeader.setSourceShipNotice(billNo);
        gdnHeader.setFactory(data.getOrgCode());
        String gdnType;
        try {
            gdnType = data.getAttribute2() == null || data.getAttribute2().equals("0")? GdnTypeEnum.D03.code : GdnTypeEnum.D02.code;
        } catch (NumberFormatException e) {
            gdnType =GdnTypeEnum.D03.code;
        }
        gdnHeader.setGdnType(gdnType);
        gdnHeader.setStatus(GdnHeaderStatusEnum.CREATE.code);
        gdnHeader.setGdnCreateTime(data.getCreateTime());
        gdnHeader.setGdnCreateUser(data.getCreateUser());
        gdnHeader.setComments(data.getRemarks());
        DataItemDetailDTO dataItem = dataItemDetailApi.getDataItemDetailByPCodeAndName(DEFAULT_OWNER, DEFAULT_OWNER_NAME);
        gdnHeader.setOwner(dataItem == null || dataItem.getItemValue() == null ? 0 : Integer.parseInt(dataItem.getItemValue()));
        gdnHeader.setPriority(0);


        gdnHeader.setGdnRef1(data.getAttribute1());//同步字段 合格标识
        gdnHeader.setGdnRef2(data.getAttribute2());//物料属性

        if (isUpdate) {
            gdnHeader.setModifyTime(new Date());
            gdnHeader.setModifyUser("system");
            gdnHeaderMapper.updateById(gdnHeader);
        } else {
            //发货单号系统生成
            String gdnNo = "";
            //生成发货单号
            try {
                gdnNo = this.basicSimpleCodeRuleApi.GenerateCode(this.gdnNoRule);
            } catch (Exception e) {
                e.printStackTrace();
                throw new SyncException(syncType, billNo, "生成发货单号失败");
            }
            gdnHeader.setGdnNo(gdnNo);
            gdnHeader.setCreateTime(new Date());
            gdnHeader.setCreateUser("system");
            gdnHeaderMapper.insert(gdnHeader);
        }
        Integer gdnLineNo = 0;
        for (IfRepackdeliveryDtl ifRepackdeliveryDtl : ifRepackdeliveryDtlList) {
            Boolean isUpdateDtl = true;
            GdnDtl gdnDtl = gdnDtlMapper.selectOne(new QueryWrapper<>(new GdnDtl().setGdnHeaderId(gdnHeader.getGdnHeaderId()).setGdnRef5(ifRepackdeliveryDtl.getAttribute5())));
            if (gdnDtl == null) {
                isUpdateDtl = false;
                gdnDtl = new GdnDtl();
                gdnDtl.setGdnLineNo(++gdnLineNo);//加个GDN_LINE_NO
            }
            gdnDtl.setGdnHeaderId(gdnHeader.getGdnHeaderId());
            gdnDtl.setSourceShipNoticeItem(ifRepackdeliveryDtl.getBillLineNo());
            Sku sku = skuMapper.selectOne(new QueryWrapper<>(new Sku().setSkuCode(ifRepackdeliveryDtl.getMaterialCode())));
            if (sku == null) {
                throw new SyncException(syncType, billNo, "物料" + ifRepackdeliveryDtl.getMaterialCode() + "不存在");
            }
            gdnDtl.setSkuId(sku.getSkuId());
            gdnDtl.setUnit(sku.getBaseUnit());
            gdnDtl.setOrderQty(ifRepackdeliveryDtl.getQty());
//            Warehouse warehouse = warehouseMapper.selectOneByWhsCode(ifRepackdeliveryDtl.getFmWhs());
//            if (warehouse == null) {
//                throw new SyncException(syncType, billNo, "仓库" + ifRepackdeliveryDtl.getFmWhs() + "不存在");
//            }
            if (ifRepackdeliveryDtl.getFmWhs() != null && data.getOrgCode() != null) {
                CodeMapping codeMapping = codeMappingNewService.selectByMappingCodeAndFacCodeAnyOne(ifRepackdeliveryDtl.getFmWhs(), data.getOrgCode());
                if (codeMapping!=null) {
                    Warehouse warehouse = warehouseMapper.selectOneByWhsCode(codeMapping.getWmsCode());
                    if (warehouse != null) {
                        gdnDtl.setWhsId(warehouse.getWhsId());
                    }
                }
            }
            gdnDtl.setGdnRef1(ifRepackdeliveryDtl.getToWhs()); //接收仓库
            gdnDtl.setGdnRef2(ifRepackdeliveryDtl.getMfgPlant()); //分厂（制造工厂）
            gdnDtl.setGdnRef3(ifRepackdeliveryDtl.getSourceId());  //来源单据号ID
            gdnDtl.setGdnRef4(ifRepackdeliveryDtl.getSourceNo()); //来源单号
            gdnDtl.setGdnRef5(ifRepackdeliveryDtl.getAttribute5()); //来源单据行号
            gdnDtl.setGdnRef7(ifRepackdeliveryDtl.getMrpUser());  //MRP控制者
            gdnDtl.setGdnRef8(ifRepackdeliveryDtl.getMrpUserDesc()); //
            gdnDtl.setGdnRef9(ifRepackdeliveryDtl.getInspNo()); //送检单号
            gdnDtl.setWorkOrder(ifRepackdeliveryDtl.getPrdWo());
            gdnDtl.setPoNo(ifRepackdeliveryDtl.getDemandNo());
            Integer qaStatus = QaStatusEnum.OK.code;
			try {
				qaStatus = data.getAttribute1() == null ?
						QaStatusEnum.WAIT.code : Integer.parseInt(data.getAttribute1());
			} catch (NumberFormatException e) {
				qaStatus = QaStatusEnum.OK.code;
			}
            gdnDtl.setQaStatus(qaStatus);  //QA状态

            if(qaStatus == QaStatusEnum.OK.code){
            	gdnDtl.setSoNo(ifRepackdeliveryDtl.getOldSoNo());
            	gdnDtl.setSoLineNo(ifRepackdeliveryDtl.getOldSoLineNo());
            } else {
            	gdnDtl.setSoNo(ifRepackdeliveryDtl.getNewSoNo());
            	gdnDtl.setSoLineNo(ifRepackdeliveryDtl.getNewSoLineNo());
            }
            gdnDtl.setComments(ifRepackdeliveryDtl.getRemarks());
            gdnDtl.setStatus(GdnDtlStatusEnum.CREATE.getCode());
            gdnDtl.setWorkCenter(ifRepackdeliveryDtl.getWorkCenter());

            if (isUpdateDtl) {
                gdnDtl.setModifyUser("system");
                gdnDtl.setModifyTime(new Date());
                gdnDtlMapper.updateById(gdnDtl);
            } else {
                gdnDtl.setCreateUser("system");
                gdnDtl.setCreateTime(new Date());
                gdnDtlMapper.insert(gdnDtl);
            }
            //设置批次号和批次属性
            Lotno lotno = lotnoService.getLotnoByGdnDtlId(gdnDtl.getGdnDtlId());
            if (lotno != null) {
                gdnDtl.setLotno(lotno.getLotno());
                int r = 1;
                try {
                    r = setLotAttr(gdnDtl, lotno);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new SyncException(syncType, billNo, "设置批次属性" + r + "失败");
                }
                gdnDtlMapper.updateLotNoAndAttr(gdnDtl);
            }
        }
        //更新状态为已同步
        int row = ifRepackdeliveryHeaderMapper.updateFlagById(data.getIfRepackdeliveryHeaderId());
        //检查是否有同步失败的记录，有则更新为成功
        JobSyncErrorData jobSyncErrorData = jobSyncErrorDataMapper.getSyncErrorDataByTypeAndCode(syncType, billNo);
        if (jobSyncErrorData != null && 0 == jobSyncErrorData.getIsSuccess()) {
            syncErrorDataService.updateSuccessByCode(syncType, billNo);
        }
    }

    /**
     * 设置批次属性1~12
     *
     * @param obj
     * @param lotno
     */
    private int setLotAttr(Object obj, Lotno lotno) throws Exception {
        int i = 1;
        for (i = 1; i < 13; i++) {
            try {
                Class<?> aClass = obj.getClass();
                Object value = lotno.getClass().getMethod("getLotAttr" + i).invoke(lotno, null);
                Method method = aClass.getMethod("setLotAttr" + i, String.class);
                method.invoke(obj, value);
            } catch (Exception e) {
                e.printStackTrace();
                break;
            }
        }
        return i;
    }

}
